;
(function() {
    var wx_access_token;
    var wx_jsapi_ticket;
    var Fiber = require('fibers');
    var crypto = require('crypto');
    var db = require("../../core/db/index");
    var config = require("../../core/_include/config");
    var ResponObj = require("../_include/responObj");
    var helper = require("../../core/_include/helper");
    var role = require("./role");
    var PayAchCon = require("../../core/pay_ach/_con");
    var AchCon = require("../../core/ach/_con");
    var BusCon = require("../../core/bus/_con");
    var midEvent = require("../../middleware/index");
    var WX = require("../../my_modules/wx/wx");
    var WX_V2 = require("../../my_modules/wx/wx.v2");
    var USER = require('../../core/user/_con');
    // var wx = new WX(appId, appSecret, mchId, Key);
    // var wx_v2 = WX_V2.dotnar_instance;
    var url = require("url");
    var querystring = require("querystring");
    var protocol_map = {
        "http:": require("http"),
        "https:": require("https")
    };

    module.exports = {
        prefix: "/wx",
        _init: function(app) {
            // console.log("获取微信公众号授权")
            // wx.get_access_token();
            // console.log(wx.access_token);

            // console.log("获取微信JS API接口授权");
            // wx.get_jsapi_ticket();
            // console.log(wx.jsapi_ticket);

            // //每10分钟自动更新一次
            // setInterval(function() {
            // 	Fiber(function () {
            // 		console.log("重新获取微信配置");
            // 		wx.get_access_token();
            // 		wx.get_jsapi_ticket();
            // 	}).run();
            // }, 10 * 60 * 1000);
        },
        get: {
            //微信ACCESS_TOKEN值，需要管理员权限
            "/access_token": function() {
                var admin = role.getAdmin(this);
                this.body = ResponObj("string", wx.access_token);
            },
            //微信JSAPI_TICKET值，需要管理员权限
            "/jsapi_ticket": function() {
                var admin = role.getAdmin(this);
                this.body = ResponObj("string", wx.jsapi_ticket);
            },
            // //获取JS API的签名
            // "/jsapi_signature": function() {
            // 	var query = this.request.query;
            // 	var headers = this.request.headers;
            // 	var url = headers["referer"];
            // 	var signature = wx.get_jsapi_signature(url, query.noncestr, query.timestamp);
            // 	signature.appId = wx.appId;
            // 	this.body = ResponObj("json", signature);
            // },
            //获取JS API的签名
            "/jsapi_signature": function() {
                var headers = this.request.headers;
                var url = headers["referer"];
                var wx_v2 = role.get_WX_V2_instance(this, this.request.query.wx_bus_id);
                var jsapi_config = wx_v2.getJsApiConfig(url);
                this.body = ResponObj("json", jsapi_config);
            },
            "/open_id": function() {
                this.body = ResponObj("string", this.cookies.get("wx_open_id") || "");
            },
            // xuezi
            "/authorize/callback": function() {
                var query = this.request.query;
                console.log(query)
                var cb_url = query.state;
                var code = query.code;
                // var user = role.getUser();
                var wx_v2 = role.get_WX_V2_instance(this);
                var web_access_token = wx_v2.getWebAccessToken(code);
                console.log("web_access_token:", web_access_token);
                var userinfo = curl('https://api.weixin.qq.com/sns/userinfo?access_token={ACCESS_TOKEN}&openid={OPENID}&lang=zh_CN'.format({
                    ACCESS_TOKEN: web_access_token.access_token,
                    OPENID: web_access_token.openid
                })).parseJSON();
                console.log(userinfo);
                try {
                    var instanceuser = USER.getByOpenId({
                        unionid: userinfo.unionid,
                        openid: web_access_token.openid
                    });
                    console.log(instanceuser);
                    role.loginUser(this, instanceuser);
                } catch (e) {
                    console.log(e);
                }
                this.cookies.set("wx_open_id", web_access_token.openid);
                var self = this;
                if (cb_url) {
                    var url_info = url.parse(cb_url);
                    console.log('url_info',url_info)
                    var http = protocol_map[url_info.protocol] || protocol_map["http:"];
                    http.get(url_info, function(res) {
                        if (res.statusCode == 301 || res.statusCode == 302) {
                            cb_url = res.headers.location;
                            url_info = url.parse(cb_url);
                        }
                        qs_info = querystring.parse(url_info.query);
                        qs_info.WEIXIN_OPENID = encodeURIComponent(web_access_token.openid || "");
                        url_info.search = "?" + querystring.stringify(qs_info);

                        cb_url = url.format(url_info);
                        console.log("重定向URL：", cb_url)
                        self.response.status(302)
                        self.response.header("Location", cb_url);
                        self.body = "";
                    });
                } else {
                    this.body = ResponObj("json", web_access_token);
                }
            },
            "/authorize/notify_url": function() {
                var query = this.request.query;
                var cb_url = query.state;
                var code = query.code;
                // var user = role.getUser();
                var wx_v2 = role.get_WX_V2_instance(this);
                var web_access_token = wx_v2.getWebAccessToken(code);
                console.log("web_access_token:", web_access_token);
                this.cookies.set("wx_open_id", web_access_token.openid);
                var self = this;
                if (cb_url) {
                    var url_info = url.parse(cb_url);
                    var http = protocol_map[url_info.protocol] || protocol_map["http:"];
                    http.get(url_info, function(res) {
                        if (res.statusCode == 301 || res.statusCode == 302) {
                            cb_url = res.headers.location;
                            url_info = url.parse(cb_url);
                        }
                        qs_info = querystring.parse(url_info.query);
                        qs_info.WEIXIN_OPENID = encodeURIComponent(web_access_token.openid || "");
                        url_info.search = "?" + querystring.stringify(qs_info);

                        cb_url = url.format(url_info);
                        console.log("重定向URL：", cb_url)
                        self.response.status(302)
                        self.response.header("Location", cb_url);
                        self.body = "";
                    });
                } else {
                    this.body = ResponObj("json", web_access_token);
                }
            },
            //获取订单的微信二维码信息，提供扫描
            "/get_ach_url_code/:ach_id": function() {
                var ach_id = this.params.ach_id;
                var query = this.request.query;
                var self = this;
                var ach = AchCon.get(ach_id);
                if (!ach) {
                    throwCusError("订单号无效");
                }
                var user = role.getUser(this);
                var pay_ach_id = user.callBackToPayAch(ach_id);
                var pay_ach = PayAchCon.get(pay_ach_id);
                var wx_v2 = role.get_WX_V2_instance(this);
                var unifiedOrderResult = wx_v2.pay_nativeUnifiedOrder({
                    _id: pay_ach_id,
                    title: "来自“{0}”的订单".format(ach.info.bus_id),
                    detail: query.detail,
                    cash: ach.finally_cash,
                    user_ip: self.request.headers["user_ip"],
                    pay_notify_security_key: pay_ach.security_key
                });
                self.body = ResponObj("json", unifiedOrderResult);
            },
            "/get_app_UnifiedOrder/:ach_id": function() {
                var ach_id = this.params.ach_id;
                var query = this.request.query;
                var self = this;
                var ach = AchCon.get(ach_id);
                if (!ach) {
                    throwCusError("订单号无效");
                }
                var user = role.getUser(this);
                var pay_ach_id = user.callBackToPayAch(ach_id);
                var pay_ach = PayAchCon.get(pay_ach_id);
                var wx_v2 = role.get_WX_V2_instance(this);
                var unifiedOrderResult = wx_v2.pay_appUnifiedOrder({
                    _id: pay_ach_id,
                    title: "来自“{0}”的订单".format(ach.info.bus_id),
                    detail: query.detail,
                    cash: ach.finally_cash,
                    user_ip: self.request.headers["user_ip"],
                    pay_notify_security_key: pay_ach.security_key
                });
                self.body = ResponObj("json", unifiedOrderResult);
            }
        },
        post: {
            "/js/unified_order": function() {
                var body = this.request.body;
                var ach_id = body.ach_id;
                if (!ach_id) {
                    throwCusError("支付订单号不可为空");
                }
                var ach = AchCon.get(ach_id);
                if (!ach) {
                    throwCusError("订单号无效");
                }
                var self = this;
                var user = role.getUser(this);
                var pay_ach_id = user.callBackToPayAch(ach_id);
                var pay_ach = PayAchCon.get(pay_ach_id);
                console.log("WEIXIN_OPENID:", this.cookies.get("wx_open_id"), body.openid);
                var openid = this.cookies.get("wx_open_id") || body.openid;
                if (!openid) {
                    throwCusError("未获取用户唯一标识");
                }
                var wx_v2 = role.get_WX_V2_instance(this);
                var chooseWXPay = wx_v2.pay_jsUnifiedOrder({
                    _id: pay_ach_id,
                    title: /*ach.info.bus_id, //*/ "来自“{0}”的订单".format(ach.info.bus_id),
                    detail: /*ach.info.bus_id + "_s_ach", //*/ body.detail,
                    cash: ach.finally_cash,
                    user_ip: self.request.headers["user_ip"],
                    openid: openid,
                    pay_notify_security_key: pay_ach.security_key
                });
                this.body = ResponObj("json", chooseWXPay);
            },
            "/order_notify": function() {
                var self = this;
                var _is_time_out = false;
                this.request.on("raw_body_parse_end", function() {
                    if (_is_time_out) {
                        return;
                    }
                    console.log("+++微信支付支付回调：+++");
                    var xmlData = self.request.rawBody;
                    console.log("---微信支付支付回调：---");
                    if (xmlData) {
                        wx.pay.pay_notify(xmlData, function(requestJson, returnJson, rawBody) {
                            console.log(requestJson, returnJson);
                            if (String(returnJson.return_code) === "SUCCESS") {
                                var pay_ach_id = String(requestJson.out_trade_no);
                                var pay_ach = PayAchCon.get(pay_ach_id);
                                if (!pay_ach) {
                                    throwCusError("找不到指定支付回调信")
                                } else {
                                    pay_ach.endPayAch();
                                    midEvent.emit("ach.online_pay_success", pay_ach_id)
                                    console.log("支付成功");
                                }
                            } else {
                                console.error(returnJson.return_msg);
                            }
                            self.body = rawBody;
                        });
                    } else {
                        self.body = "NOTIFY ERROR";
                    }
                });
                setTimeout(function() {
                    _is_time_out = true;
                    if (!self.body) {
                        self.body = "RAW PARSE TIME OUT";
                    }
                }, 30 * 1000); //30s超时
            },
            // 2016060451858634
            "/getPayach": function() {
                var self = this;
                var data = self.request.body;
                var pay_ach_id = String(data.id);
                var pay_ach = PayAchCon.get("PA_" + pay_ach_id);
                var pay_ach2 = PayAchCon.get2(pay_ach_id);
                // pay_ach2.endPayAch()
                pay_ach2.type = 2
                self.body = pay_ach || pay_ach2;
            },
            "/app_pay_notify": function() {
                var self = this;
                var data = self.request.body;
                var pay_ach_id = String(data.out_trade_no);
                var pay_ach = PayAchCon.get2(pay_ach_id);
                console.log("pay_ach:", pay_ach);
                if (!pay_ach) {
                    throwCusError("找不到支付信息");
                } else {
                    pay_ach.endPayAch();
                    // midEvent.emit("ach.online_pay_success", pay_ach_id)
                    console.log("支付成功");
                };
                self.body = data;
            },
            "/success_order_notify/from/jjy/java_tools/weixin": function() {
                var body = this.request.body;
                console.log("JJY JAVA BODY:", body);
                var pay_ach_id = body.out_trade_no;
                var security_key = body.securityKey;
                var pay_ach = PayAchCon.get(pay_ach_id);
                if (!pay_ach) {
                    throwCusError("ORDER NOTIFY ERROR:out_trade_no 无效（找不到指定支付回调信息）");
                }
                if (pay_ach.security_key !== security_key) { //不使用微信提供的KEY，为了KEY安全与破解难度，也简化了计算量（空间换时间）
                    throwCusError("ORDER NOTIFY ERROR:security_key 无效（支付回调安全密匙不匹配）");
                }
                pay_ach.endPayAch();
                midEvent.emit("ach.online_pay_success", pay_ach_id)
                console.log("支付成功");
                this.body = ResponObj("string", "SUCCESS");
            }
        }
    }
}());
